package com.kg.tombs.utils;

import io.vertx.core.json.JsonObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class CsvParser {


    public static List<JsonObject> parse(InputStream inputStream) throws Exception {
        List<JsonObject> result = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        String[] headers = null;
        StringBuilder multiLineBuffer = new StringBuilder();
        boolean inMultiLineField = false;

        int lineNumber = 0;
        while ((line = reader.readLine()) != null) {
            // 跳过空行
            if (line.trim().isEmpty() && !inMultiLineField) {
                continue;
            }

            // 检查是否在多行字段中
            if (inMultiLineField) {
                multiLineBuffer.append("\n").append(line);
            } else {
                multiLineBuffer.append(line);
            }

            // 检查当前缓冲区是否包含完整的记录（引号匹配）
            String bufferContent = multiLineBuffer.toString();
            long quoteCount = bufferContent.chars().filter(ch -> ch == '"').count();

            // 如果引号数量为偶数，表示字段完整
            if (quoteCount % 2 == 0) {
                String[] values = parseLine(multiLineBuffer.toString());

                if (lineNumber == 0) {
                    headers = values;
                } else {
                    JsonObject row = new JsonObject();
                    // 确保不会因为列数不匹配而丢失数据
                    int minColumns = Math.min(headers.length, values.length);
                    for (int i = 0; i < minColumns; i++) {
                        row.put(headers[i].trim(), values[i]);
                    }
                    // 如果values比headers多，仍然添加这些额外的值
                    for (int i = headers.length; i < values.length; i++) {
                        row.put("column_" + (i + 1), values[i]);
                    }
                    result.add(row);
                }

                lineNumber++;
                multiLineBuffer.setLength(0); // 清空缓冲区
                inMultiLineField = false;
            } else {
                inMultiLineField = true;
            }
        }

        return result;
    }

    /**
     * 解析CSV行，正确处理引号和转义字符
     */
    private static String[] parseLine(String line) {
        List<String> result = new ArrayList<>();
        boolean inQuotes = false;
        StringBuilder currentField = new StringBuilder();

        for (int i = 0; i < line.length(); i++) {
            char ch = line.charAt(i);

            if (ch == '"' && (i == 0 || line.charAt(i - 1) != '\\')) {
                // 切换引号状态
                inQuotes = !inQuotes;
            } else if (ch == ',' && !inQuotes) {
                // 字段分隔符
                result.add(currentField.toString().trim());
                currentField = new StringBuilder();
            } else {
                // 普通字符
                currentField.append(ch);
            }
        }

        // 添加最后一个字段
        result.add(currentField.toString().trim());

        return result.toArray(new String[0]);
    }



//    public static List<JsonObject> parse(InputStream inputStream) throws Exception {
//        List<JsonObject> result = new ArrayList<>();
//        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//        String line;
//        String[] headers = null;
//
//        int lineNumber = 0;
//        while ((line = reader.readLine()) != null) {
//            String[] values = line.split(",");
//            if (lineNumber == 0) {
//                headers = values;
//            } else {
//                JsonObject row = new JsonObject();
//                for (int i = 0; i < headers.length && i < values.length; i++) {
//                    row.put(headers[i].trim(), values[i].trim());
//                }
//                result.add(row);
//            }
//
//            lineNumber++;
//        }
//
//        return result;
//    }

}
